package com.fangmao.jetpack.room;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.fangmao.jetpack.R;

import java.util.Date;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

public class RoomActivity extends AppCompatActivity {
    WordViewModel mWordViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room);

        mWordViewModel = ViewModelProviders.of(this).get(WordViewModel.class);

        mWordViewModel.getAllWordLive().observe(this, new Observer<List<Word>>() {
            @Override
            public void onChanged(List<Word> words) {
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < words.size(); i++) {
                    Word word = words.get(i);
                    builder.append(builder.length() > 0 ? "\n" : "").append(word.getId()).append(":").append(word.getWord()).append(" -> ").append(word.getChineseMeaning());
                }
                ((TextView) findViewById(R.id.textView)).setText(builder.toString());
            }
        });

        findViewById(R.id.buttonInsert).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Word word = new Word("Hello:" + new Date().getDate(), "您好:" + new Date().getDate());
                mWordViewModel.insertWord(word);
            }
        });
        findViewById(R.id.buttonUpdate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Word word = new Word("Hello:" + new Date().getDate(), "您好:" + new Date().getDate());
                word.setId(1);
                mWordViewModel.updateWord(word);
            }
        });
        findViewById(R.id.buttonDelete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Word word = new Word("Hello:" + new Date().getDate(), "您好:" + new Date().getDate());
                word.setId(1);
                mWordViewModel.deleteWord(word);
            }
        });
        findViewById(R.id.buttonClear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mWordViewModel.clearWord();
            }
        });
    }
}
